package com.maxd.modules.selfshop.prize.service.impl;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.JiFen;
import com.maxd.modules.selfshop.prize.entity.SelfPrizeRule;
import com.maxd.modules.selfshop.prize.entity.SelfPrizeUser;
import com.maxd.modules.selfshop.prize.respository.SelfPrizeRuleJpaRepository;
import com.maxd.modules.selfshop.prize.respository.SelfPrizeUserJpaRepository;
import com.maxd.modules.selfshop.prize.service.SelfPrizeUserService;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.jifen.IJiFenService;
import com.maxd.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class SelfPrizeUserServiceImpl implements SelfPrizeUserService {
    @Autowired
    private SelfPrizeUserJpaRepository jpaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private IJiFenService jiFenService;
    @Autowired
    private SelfPrizeRuleJpaRepository selfPrizeRuleJpaRepository;

    @Override
    public Result findAll(Integer page, Integer size, String nickName) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        Specification<SelfPrizeUser> queryCondition = new Specification<SelfPrizeUser>() {
            @Override
            public Predicate toPredicate(Root<SelfPrizeUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(nickName)) {
                    predicateList.add(criteriaBuilder.like(root.get("nickName"), "%"+nickName+"%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }


    @Override
    public Result userList(Integer page, Integer size, Long userId) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        Specification<SelfPrizeUser> queryCondition = new Specification<SelfPrizeUser>() {
            @Override
            public Predicate toPredicate(Root<SelfPrizeUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("userId"), userId));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result saveBody(SelfPrizeUser e) {
        //抽奖记录保存
        e.setCreateTime(DateUtil.createTime());
        SelfPrizeUser save = jpaRepository.save(e);
        //积分信息
        Long userId = e.getUserId();
        String lessJiFen = e.getLessJiFen();
        String addJiFen = e.getAddJiFen();
        //处理用户减少
        userRepository.lessOrderJifen(lessJiFen, userId);
        JiFen jiFen = new JiFen();
        jiFen.setCreateAt(DateUtil.createTime());
        jiFen.setNumber(lessJiFen);
        jiFen.setUserId(userId.toString());
        jiFen.setContent("积分兑换");
        jiFen.setDes("抽奖消耗-"+lessJiFen);
        jiFenService.saveBody(jiFen);
        //积分增多
        if (!"0".equals(addJiFen)){
            JiFen jiFen1 = new JiFen();
            jiFen1.setCreateAt(DateUtil.createTime());
            jiFen1.setNumber(addJiFen);
            jiFen1.setUserId(userId.toString());
            jiFen1.setDes("抽奖添加+"+addJiFen);
            jiFenService.saveBody(jiFen1);
            userRepository.addOrderJifen(e.getAddJiFen(), e.getUserId());
        }
        return ResultUtil.success(save);
    }

    @Override
    public Result updateBody(SelfPrizeUser entity) {
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    @Override
    public Result checkNumber(Long prizeRuleId, Long userId) {
        SelfPrizeRule selfPrizeRule = selfPrizeRuleJpaRepository.findById(prizeRuleId).orElse(null);
        int sum = selfPrizeRule.getNumber().intValue();
        int count = jpaRepository.findCountByUserId(userId, DateUtil.createDate());
        return ResultUtil.success(sum-count); //剩余次数
    }

}
